<template>
  <div class="news-manage">
    <TopBar />
    <div class="content">
      <MenuLine />
      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog">添加新闻</el-button>
      </div>

      <el-table :data="newsList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="封面" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.coverUrl"
              :src="row.coverUrl"
              fit="cover"
              style="width: 100px; height: 60px; border-radius: 4px;"
            />
            <span v-else>无封面</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="250" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteNews(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%" @close="resetForm">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入新闻标题" />
          </el-form-item>

          <el-form-item label="封面图片" prop="coverUrl">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleCoverChange"
            >
              <el-image v-if="form.coverUrl" :src="form.coverUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="内容" prop="content">
            <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入新闻内容" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useNewsStore, type News } from '@/stores/news';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

const newsStore = useNewsStore();
const newsList = ref<News[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref('添加新闻');
const isEdit = ref(false);
const form = ref<News>({
  id: 0,
  title: '',
  content: '',
  coverUrl: '',
  createTime: '',
});
const formRef = ref<FormInstance>();
const rules = ref<FormRules>({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在1到100字符', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 1, max: 1000, message: '内容长度在1到1000字符', trigger: 'blur' },
  ],
});

const fetchNewsList = async () => {
  try {
    const result = await newsStore.fetchNewsList();
    newsList.value = Array.isArray(result) ? result : []; // 确保是数组
  } catch (error) {
    ElMessage.error('获取新闻列表失败');
    newsList.value = []; // 出错时设为空数组
  }
};

const handleCoverChange = async (file: any) => {
  try {
    const url = await newsStore.uploadCover(file.raw);
    form.value.coverUrl = url;
    ElMessage.success('封面图片上传成功');
  } catch (error) {
    ElMessage.error('封面图片上传失败');
  }
};

const openAddDialog = () => {
  isEdit.value = false;
  dialogTitle.value = '添加新闻';
  dialogVisible.value = true;
};

const openEditDialog = (row: News) => {
  isEdit.value = true;
  dialogTitle.value = '编辑新闻';
  form.value = { ...row };
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await newsStore.updateNews(form.value);
          ElMessage.success('编辑新闻成功');
        } else {
          await newsStore.createNews(form.value);
          ElMessage.success('添加新闻成功');
        }
        dialogVisible.value = false;
        await fetchNewsList();
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑新闻失败' : '添加新闻失败');
      }
    }
  });
};

const deleteNews = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除该新闻吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await newsStore.deleteNews(id);
    ElMessage.success('删除新闻成功');
    await fetchNewsList();
  } catch (error) {
    ElMessage.info('取消删除');
  }
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = { id: 0, title: '', content: '', coverUrl: '', createTime: '' };
};

onMounted(() => {
  fetchNewsList();
});
</script>

<style scoped>
.news-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px;
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px;
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 100px;
  display: block;
}
</style>